

import React, { Component } from 'react';
import {Button,Table,Tag,Popconfirm,Modal,Form,Select,Input, message,} from "antd"
import {DeleteOutlined,FormOutlined,UserOutlined,LockOutlined,MoneyCollectOutlined,PhoneOutlined} from "@ant-design/icons"
import userlist from '../../mobx/userlist';
import myuser from "../../mobx/myuser";
import {observer} from "mobx-react";
import { roleList, xinbie } from '../../utils';
import moment from "moment"
import { ajax } from '../../api';
import {passReg,phoneReg,usernameReg} from "../../utils/validate"


const layout = {
    labelCol: { offset:6,span: 12 },
    wrapperCol: { offset:6 , span: 12 },
};
const { Search } = Input;
const {Option} = Select
@observer
class UserList extends Component {

    state={
        columns:[
            {
                title:"序号",
                dataIndex:"index",
                key:"index",
                align:"center",
                render:(text,item,index)=>{
                    return index+1
                }
            },
            {
                title:"员工姓名",
                align:"center",
                key:"username",
                dataIndex:"username",
            },
            {
                title:"手机号码",
                align:"center",
                key:"phone",
                dataIndex:"phone",
            },
            {
                title:"员工职位",
                align:"center",
                render:(text,item,index)=>{
                    return  (<Tag color={roleList[item.role].color}>{roleList[item.role].name} </Tag>)
                }
            },
            {
                title:"性别",
                align:"center",
                render:(text,item,index)=>{
                    return (<Tag color={xinbie[item.sex].color}>{xinbie[item.sex].name}</Tag>)
                }
            },
            {
                title:"入职时间",
                align:"center",
                render:(text)=>{
                    return moment(text.time).format("YYYY-MM-DD HH:mm:ss")
                }
            },
            {
                title:"薪资",
                align:"center",
                render:(text,item,index)=>{
                    return (
                        (myuser.user.role&&myuser.user.role>=roleList.length-1)?item.xinzi:"暂无权限"
                    )
                }
            },
            {
               title:"操作",
               align:"center",
               render:(text,item,index)=>{
                   const {user} = myuser
                   return (
                       <div>
                           <Popconfirm
                                title="您确定要删除当前用户吗？"
                                onConfirm={()=>this.delconfirm(item,index)}
                                okText="确定"
                                cancelText="取消"
                                disabled={user.role&&item.role*1 >= user.role*1}
                            >
                                <Button disabled={user.role&&item.role*1 >= user.role*1} style={{marginRight:10}}  icon={<DeleteOutlined />} type="danger" shape="circle"></Button>
                            </Popconfirm>
                            {(user.role&&user.role>=roleList.length-1)&&<Button disabled={item.role*1 >= user.role*1} onClick={()=>this.showUpdateVisible(item)} icon={<FormOutlined />} type="primary" shape="circle"></Button>}
                       </div>
                   )
               } 
            }
        ],
        addvisible:false,
        updatevisible:false,
        detail:{}
    }

    delconfirm=(item,index)=>{
        ajax.deluserone({
            _id:item._id
        }).then(res=>{
            if(res.code==200){
                var list = userlist.allList.filter(value=>value._id!=item._id)
                userlist.changeAllList(list)
            }
        })
    }

    showUpdateVisible=(item)=>{
        this.setState({
            updatevisible:true,
            detail:item
        },()=>{
            this.updateform.setFieldsValue(item)
        })

    }

    componentDidMount(){
        userlist.getAllList()
    }

    addSubmit=()=>{
        this.addform.validateFields().then(value=>{
            console.log(value)
            ajax.register(value).then(res=>{
                if(res.code==200){
                    this.setState({
                        addvisible:false
                    })
                    userlist.getAllList()
                    this.addform.resetFields()
                }
            })
        }).catch(err=>{
            message.error("请先完善信息后再提交")
        })
    }


    showAddModal=()=>{
        this.setState({
            addvisible:true
        })
    }

    updateCancel=()=>{
        this.setState({
            updatevisible:false,
        })
    }

    addCancel=()=>{
        this.setState({
            addvisible:false
        })
        this.addform.resetFields()
    }

    updateSubmit=()=>{
        this.updateform.validateFields().then(value=>{
            ajax.updateuserrole({_id:this.state.detail._id,...value}).then(res=>{
                if(res.code==200){
                    this.setState({
                        updatevisible:false,
                    })
                    var list = userlist.allList.map(item=>{
                        if(item._id==this.state.detail._id){
                            item={...item,...value}
                        }
                        return item
                    })
                    userlist.changeAllList(list)
                    this.updateform.resetFields()
                }
            })
        })
    }

    onSearch=()=>{
        var keyword = this.SearchInp.state.value
        userlist.getAllList(keyword)
    }

    //导出Excel
    donwloadExcel=(table,name)=>{
        if(userlist.allList.length>0){

            var uri = "data:application/vnd.ms-excel;base64,",
            template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
            base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) },
            format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) };

            if(!table.nodeType) table =document.getElementById(table)
            var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}

            var filename ="员工信息"+moment().format("L")+".xls";
            document.getElementById("dlink").href = uri + base64(format(template, ctx));
            document.getElementById("dlink").download = filename;
            document.getElementById("dlink").click();
        }else{
            message.error("请等待数据载入后再导出")
        }
    }

    render() {
        const {user} = myuser
        return (
            <div>
                <h2 style={{textAlign:"center",color:"#f00",fontSize:30,fontWeight:600}}>员工列表</h2>
                <div style={{display:"flex",justifyContent:"space-between",alignItems:"center"}}>
                    <div>
                        <Button type="danger" style={{marginRight:10}} onClick={this.showAddModal}>新增员工</Button>
                        <a id="dlink"  style={{display:'none'}}></a>
                        <Button type="primary" onClick={()=>this.donwloadExcel('mytable','员工信息')}>导出 Excel</Button>
                    </div>
                    <Search placeholder="搜索员工信息" enterButton="搜索" style={{width:350}} ref={el=>this.SearchInp=el}   onSearch={this.onSearch}/>
                </div>
                
                <Table id="mytable" columns={this.state.columns} dataSource={userlist.allList} style={{marginTop:15}} bordered pagination={{pageSize:10}} rowKey={
                        (item)=>(item._id)
                    }/>

                <Modal
                    title="新增用户"
                    visible={this.state.addvisible}
                    onOk={this.addSubmit}
                    onCancel={this.addCancel}
                    okText="确定新增"
                    cancelText="取消"
                >
                    <Form
                        name="addForm"
                        ref={el=>this.addform=el}
                        layout="vertical"
                        className="form-box"
                        {...layout}
                        initialValues={{ 
                            password:123456
                        }}
                    >
                        <Form.Item
                            label="员工姓名"
                            name="username"
                            rules={[{ required: true, message: '请输入员工姓名' },
                            {
                                pattern:usernameReg,message:"请填写2-4位的汉字姓名"
                            }]}
                        >
                            <Input  prefix={<UserOutlined  className="login-icon-color" /> }  />
                        </Form.Item>
                        <Form.Item
                            label="登录密码"
                            name="password"
                            rules={[
                                { required: true, message: '请输入密码!' },
                                {
                                    pattern:passReg,
                                    message:"请输入6-12的合法密码!"
                                }
                            ]}
                        >
                            <Input.Password disabled prefix={<LockOutlined  className="login-icon-color"  />} />
                        </Form.Item>
                        <Form.Item
                            label="手机号码"
                            name="phone"
                            rules={[
                                { required: true, message: '请输入手机号码!' },
                                {pattern:phoneReg,message:"请输入正确手机号码"}
                            ]}
                            
                        >
                            <Input type="tel"  placeholder="手机号码" prefix={<PhoneOutlined  className="login-icon-color"   />} />
                        </Form.Item>
                        <Form.Item
                            label="权限"
                            name="role"
                            rules={[
                                { required: true, message: '请选择!' },
                            ]}
                            
                        >
                           <Select>
                                {
                                    roleList.map((l,i)=>{
                                        return (
                                           (user.role&& user.role * 1 > l.id * 1  )&&<Option key={i} value={l.id}>
                                                {l.name}
                                            </Option>
                                        )
                                    })
                                }
                           </Select>
                        </Form.Item>
                        <Form.Item
                            label="性别"
                            name="sex"
                            rules={[
                                { required: true, message: '请选择!' },
                            ]}
                        >
                           <Select>
                                {
                                    xinbie.map((l,i)=>{
                                        return (
                                            <Option key={i} value={l.id}>
                                                {l.name}
                                            </Option>
                                        )
                                    })
                                }
                           </Select>
                        </Form.Item>

                        {
                            user.role>=roleList.length-1&&<Form.Item
                            label="薪资"
                            name="xinzi"
                            rules={[
                                { required: true, message: '请输入薪资!' },
                                {pattern:/^[1-9][\d]*\.[\d]{2}$/,message:"请输入正确金额(需保留小数点后两位)"}
                            ]}
                            
                        >
                            <Input type="text"  placeholder="薪资" prefix={<MoneyCollectOutlined  className="login-icon-color"   />} />
                        </Form.Item>
                        }
                    </Form>
                </Modal>
           
                {/* 更改用户 */}
                <Modal
                    title="更改用户"
                    visible={this.state.updatevisible}
                    onOk={this.updateSubmit}
                    onCancel={this.updateCancel}
                    okText="确定新增"
                    cancelText="取消"
                >
                    <Form
                        name="updateForm"
                        ref={el=>this.updateform=el}
                        layout="vertical"
                        className="form-box"
                        {...layout}
                    >
                        <Form.Item
                            label="员工姓名"
                            name="username"
                            rules={[{ required: true, message: '请输入员工姓名' },
                            {
                                pattern:usernameReg,message:"请填写2-4位的汉字姓名"
                            }]}
                        >
                            <Input disabled prefix={<UserOutlined  className="login-icon-color" /> }  />
                        </Form.Item>

                        <Form.Item
                            label="登录密码"
                            name="password"
                            rules={[
                                { required: true, message: '请输入密码!' },
                                {
                                    pattern:passReg,
                                    message:"请输入6-12的合法密码!"
                                }
                            ]}
                        >
                            <Input.Password disabled prefix={<LockOutlined  className="login-icon-color"  />} />
                        </Form.Item>
                        <Form.Item
                            label="手机号码"
                            name="phone"
                            rules={[
                                { required: true, message: '请输入手机号码!' },
                                {pattern:phoneReg,message:"请输入正确手机号码"}
                            ]}
                            
                        >
                            <Input type="tel" disabled placeholder="手机号码" prefix={<PhoneOutlined  className="login-icon-color"   />} />
                        </Form.Item>
                        <Form.Item
                            label="权限"
                            name="role"
                            rules={[
                                { required: true, message: '请选择!' },
                            ]}
                            
                        >
                           <Select>
                                {
                                    roleList.map((l,i)=>{
                                        return (
                                           (user.role&& user.role * 1 > l.id * 1  )&&<Option key={i} value={l.id}>
                                                {l.name}
                                            </Option>
                                        )
                                    })
                                }
                           </Select>
                        </Form.Item>
                        <Form.Item
                            label="性别"
                            name="sex"
                            rules={[
                                { required: true, message: '请选择!' },
                            ]}
                        >
                           <Select disabled>
                                {
                                    xinbie.map((l,i)=>{
                                        return (
                                            <Option key={i} value={l.id}>
                                                {l.name}
                                            </Option>
                                        )
                                    })
                                }
                           </Select>
                        </Form.Item>
                        {
                            user.role>=roleList.length-1&&<Form.Item
                            label="薪资"
                            name="xinzi"
                            rules={[
                                { required: true, message: '请输入薪资!' },
                                {pattern:/^[1-9][\d]*\.[\d]{2}$/,message:"请输入正确金额(需保留小数点后两位)"}
                            ]}
                            
                        >
                            <Input type="text"  placeholder="薪资" prefix={<PhoneOutlined  className="login-icon-color"   />} />
                        </Form.Item>
                        }
                    </Form>
                </Modal>
            </div>
        );
    }
}

export default UserList;